package com.bsj.power.system.web;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.system.SystemUtil;
import com.bsj.power.common.config.global.JsonResult;
import com.bsj.power.common.def.vo.sys.alert.IAlertMonitorSearchVO;
import com.bsj.power.common.def.vo.sys.alert.IAlertValueVO;
import com.bsj.power.common.def.vo.sys.alert.OAlertValueVO;
import com.bsj.power.common.def.vo.sys.alert.OInstanceVO;
import com.bsj.power.common.util.ExceptionUtil;
import com.bsj.power.common.util.HttpUtil;
import com.bsj.power.system.service.AlertManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;

/**
 * @author : zhuojie.c
 * @version V1.0
 * @Description: TODO
 * @date Date : 2024年08月22日
 */
@SaIgnore
@Slf4j
@RestController
@RequestMapping("/system/alertManager")
//@SaCheckPermission("/master/system/monitor")
public class AlertManagerController {

    @Autowired
    private AlertManagerService alertManagerService;

    public static final Long INTERVAL = 604799L;

    @Value("${prometheus.url}")
    public String url;

//    @Value("${prometheus.greptimedb}")
//    public String greptimedb;
//
//    @Value("${prometheus.username}")
//    public String username;
//
//    @Value("${prometheus.password}")
//    public String password;
//
//    /**
//     * 前缀-GreptimeDB 实现了兼容 Prometheus 的一系列 API
//     */
//    private final String path = "/v1/prometheus/api/v1/query_range?query=";

    /**
     * 接收alertmanager服务器性能告警消息
     *
     * @param payload
     * @return
     */
    @SaIgnore
    @PostMapping("/send")
    public ResponseEntity<String> send(@RequestBody(required = false) String payload) {
        log.info("SYSTEM ALERT_MANAGER SEND:{}", payload);
        alertManagerService.send(payload);
        return ResponseEntity.ok("Webhook received");
    }

    /**
     * 设置服务器报警阀值
     *
     * @param alertValueVO
     * @return
     */
    @PostMapping("/setAlertValue")
    public JsonResult setAlertValue(@Validated @RequestBody IAlertValueVO alertValueVO) {
        return alertManagerService.setAlertValue(alertValueVO);
    }

    /**
     * 获取服务器报警阀值
     *
     * @return
     */
    @GetMapping("/getAlertValue")
    public JsonResult<OAlertValueVO> getAlertValue() {
        return alertManagerService.getAlertValue();
    }

    /**
     * 获取服务器实例列表
     *
     * @return
     */
    @GetMapping("/getInstanceList")
    public JsonResult<List<OInstanceVO>> getInstanceList() {
        List<OInstanceVO> list = new LinkedList<>();
        String hostAddress = "10.0.0";
        try {
            // 获取本机的InetAddress实例
            InetAddress localHost = InetAddress.getLocalHost();
            // 获取IP地址字符串
            hostAddress = localHost.getHostAddress();
            System.out.println("本机的IP地址是: " + hostAddress);
        } catch (UnknownHostException e) {
            log.error("UnknownHostException:{}", ExceptionUtil.getStackStr(e));
        }
        if (SystemUtil.getHostInfo().getAddress().startsWith(hostAddress)) {
            list.add(new OInstanceVO("10.0.0.59", "10.0.0.59:9100"));
            list.add(new OInstanceVO("10.0.0.60", "10.0.0.60:9100"));
            list.add(new OInstanceVO("10.0.0.61", "10.0.0.61:9100"));

//            list.add(new OInstanceVO("10.0.0.59", "zh1"));
//            list.add(new OInstanceVO("10.0.0.60", "zh2"));
//            list.add(new OInstanceVO("10.0.0.61", "iZwz91zmez5yhon20ufq3vZ"));
        } else {
            list.add(new OInstanceVO("10.18.50.3", "10.18.50.3:9100"));
            list.add(new OInstanceVO("10.18.50.4", "10.18.50.4:9100"));
            list.add(new OInstanceVO("10.18.50.5", "10.18.50.5:9100"));
            list.add(new OInstanceVO("10.18.50.6", "10.18.50.6:9100"));
            list.add(new OInstanceVO("10.18.50.7", "10.18.50.7:9100"));
            list.add(new OInstanceVO("10.18.50.8", "10.18.50.8:9100"));
            list.add(new OInstanceVO("10.18.50.9", "10.18.50.9:9100"));
            list.add(new OInstanceVO("10.18.50.10", "10.18.50.10:9100"));
            list.add(new OInstanceVO("10.18.50.11", "10.18.50.11:9100"));
            list.add(new OInstanceVO("10.18.50.12", "10.18.50.12:9100"));
        }
        return JsonResult.success(list);
    }

    /**
     * 服务器CPU使用率
     *
     * @param searchVO
     * @return
     */
    @GetMapping("/cpuUsage")
    public JsonResult<String> cpuUsage(@Validated IAlertMonitorSearchVO searchVO) {
        Long startTime = Long.parseLong(searchVO.getStartTime());
        Long endTime = Long.parseLong(searchVO.getEndTime());
        String step = "60";
        if (endTime - startTime > INTERVAL) {
            step = "3600";
        }
        // Prometheus 版本
         return JsonResult.success(cn.hutool.http.HttpUtil.get(url + "100+-+(avg+by+(instance)+(rate(node_cpu_seconds_total{mode=\"idle\",instance=\"" + searchVO.getInstance() + "\"}[5m]))+*+100)&start=" + searchVO.getStartTime() + "&end=" + searchVO.getEndTime() + "&step=" + step));

//        String responseBody = HttpUtil.doGetAuth(greptimedb + path + "cpu_usage_user{agent_hostname=\"" + searchVO.getInstance() + "\"}&start=" + searchVO.getStartTime() + "&end=" + searchVO.getEndTime() + "&step=" + step, username, password);
//        return JsonResult.success(responseBody);
    }

    /**
     * 服务器内存使用率
     *
     * @param searchVO
     * @return
     */
    @GetMapping("/memoryUsage")
    public JsonResult<String> memoryUsage(@Validated IAlertMonitorSearchVO searchVO) {
        Long startTime = Long.parseLong(searchVO.getStartTime());
        Long endTime = Long.parseLong(searchVO.getEndTime());
        String step = "60";
        if (endTime - startTime > INTERVAL) {
            step = "3600";
        }
        // Prometheus 版本
         return JsonResult.success(cn.hutool.http.HttpUtil.get(url + "(1+-+node_memory_MemAvailable_bytes{instance=\"" + searchVO.getInstance() + "\"}+/+node_memory_MemTotal_bytes{instance=\"" + searchVO.getInstance() + "\"})+*+100+&start=" + searchVO.getStartTime() + "&end=" + searchVO.getEndTime() + "&step=" + step));

//        String responseBody = HttpUtil.doGetAuth(greptimedb + path + "mem_used_percent{agent_hostname=\"" + searchVO.getInstance() + "\"}&start=" + searchVO.getStartTime() + "&end=" + searchVO.getEndTime() + "&step=" + step, username, password);
//        return JsonResult.success(responseBody);
    }

    /**
     * 服务器硬盘使用率
     *
     * @param searchVO
     * @return
     */
    @GetMapping("/diskUsage")
    public JsonResult<String> diskUsage(@Validated IAlertMonitorSearchVO searchVO) {
        Long startTime = Long.parseLong(searchVO.getStartTime());
        Long endTime = Long.parseLong(searchVO.getEndTime());
        String step = "60";
        if (endTime - startTime > INTERVAL) {
            step = "3600";
        }
        // Prometheus 版本
         return JsonResult.success(cn.hutool.http.HttpUtil.get(url + "100+-+(node_filesystem_avail_bytes{fstype=~\"ext4|xfs\",instance=\"" + searchVO.getInstance() + "\"}+/+node_filesystem_size_bytes{fstype=~\"ext4|xfs\",instance=\"" + searchVO.getInstance() + "\"})+*+100+&start=" + searchVO.getStartTime() + "&end=" + searchVO.getEndTime() + "&step=" + step));

//        String responseBody = HttpUtil.doGetAuth(greptimedb + path + "disk_used_percent{agent_hostname=\"" + searchVO.getInstance() + "\"}&start=" + searchVO.getStartTime() + "&end=" + searchVO.getEndTime() + "&step=" + step, username, password);
//        return JsonResult.success(responseBody);
    }
}
